package com.calm.editor.servlet;

import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.nio.CharBuffer;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.servlet.http.HttpServletRequest;

import org.apache.catalina.websocket.StreamInbound;
import org.apache.catalina.websocket.WsOutbound;
import org.springframework.context.ApplicationContext;

@SuppressWarnings("deprecation")
public class HelloMessageInbound extends StreamInbound {
	
	private ApplicationContext context;
	private ExecutorService pool = Executors.newFixedThreadPool(100);
	private HttpServletRequest request;
	public HelloMessageInbound(ApplicationContext context, HttpServletRequest request) {
		this.context = context;
		this.setRequest(request);
	}
	
	@Override
	protected void onOpen(WsOutbound outbound) {
		super.onOpen(outbound);
	}

	public void send(String message) throws IOException {
		getWsOutbound().writeTextMessage(CharBuffer.wrap(message));
	}
	@Override
	protected void onBinaryData(InputStream is) throws IOException {
		// TODO Auto-generated method stub
		
	}

	@Override
	protected void onTextData(Reader r) throws IOException {
		CharBuffer wrap = CharBuffer.allocate(1024*1024);
		int read = r.read(wrap);
		String string = new String(wrap.subSequence(0, read).array());
		pool.execute(new HandlerExecuter(string,context,this) );
		
	}

	public HttpServletRequest getRequest() {
		return request;
	}

	public void setRequest(HttpServletRequest request) {
		this.request = request;
	}
}